﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Windows.Threading;
using Infragistics.Composite.Wpf.Samples.SearchModule.Properties;

namespace Infragistics.Composite.Wpf.Samples.SearchModule
{
    public partial class SearchView : UserControl
    {
        public SearchView()
        {
            InitializeComponent();
        }

        void OnSearchButtonClick(object sender, RoutedEventArgs e)
        {
            this.loadingMessage.Visibility = Visibility.Visible;
            this.loadingMessage.InvalidateMeasure();
            this.loadingMessage.InvalidateArrange();
            this.loadingMessage.InvalidateVisual();
            this.loadingMessage.UpdateLayout();

            // Give the loading message a chance to render before starting the search.
            base.Dispatcher.BeginInvoke(
                DispatcherPriority.SystemIdle,
                (Action)delegate
                {
                    SearchViewModel viewModel = base.DataContext as SearchViewModel;
                    if (viewModel != null && viewModel.SearchCommand.CanExecute(null))
                        viewModel.SearchCommand.Execute(null);
                });
        }

        void Frame_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            base.Cursor = Cursors.Wait;
        }

        void Frame_LoadCompleted(object sender, NavigationEventArgs e)
        {
            base.Cursor = Cursors.Arrow;
            this.loadingMessage.Visibility = Visibility.Collapsed;
        }

        void Frame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            this.loadingMessage.Visibility = Visibility.Collapsed;

            MessageBox.Show(
                e.Exception.Message, 
                Strings.SearchViewModel_ErrorMessageBoxTitle, 
                MessageBoxButton.OK, 
                MessageBoxImage.Error);

            base.Cursor = Cursors.Arrow;
            e.Handled = true;
        }
    }
}